'use strict';

const moment = require('moment');

const Controller = require('../../core/common');

class IntegralInsController extends Controller {

  async create() {

    const { ctx } = this;

    const { userId = 0 } = ctx.request.body;

    const total = await ctx.model.IntegralIns.max('total', { where: { userId } }) || 0;
    // 获取今天收获的幸运草数量
    const sum = await ctx.model.IntegralIns.sum('number', {
      where: { userId, createdAt: { '$between': [moment().format('YYYY-MM-DD'), moment().add(1, 'days').format('YYYY-MM-DD')] } }
    }) || 0;
    // 今天过了几个小时
    const current = moment().format('HH');
    // 数据当前日期
    const currentAt = moment().format('YYYY-MM-DD HH:mm:ss');
    if (sum >= 24) return this.success(24, '今日已领取完~');
    if (sum >= current && sum <= 24) return this.success(sum, '还在生产中~');
    if (sum <= current) {
      // 收获写入数据库 -- type === 2收获
      const number = current - sum;
      const data = await ctx.model.IntegralIns.create({
        userId,
        total: total ? total + number : number,
        number,
        type: 2,
        createdAt: currentAt,
        updatedAt: currentAt,
      });

      return this.success(data, `成功领取 ${number} 棵~`);
    }

    this.success(null, '不知道你做了什么', -1);
  }
}

module.exports = IntegralInsController;